package com.zhiwei.codesecurity.web.api.user.controller;

import com.zhiwei.codesecurity.common.base.NullObjectResp;
import com.zhiwei.codesecurity.common.base.ServiceResponse;
import com.zhiwei.codesecurity.common.enums.ResultCode;
import com.zhiwei.codesecurity.common.utils.*;
import com.zhiwei.codesecurity.entity.Users;
import com.zhiwei.codesecurity.service.users.IUserService;
import com.zhiwei.codesecurity.service.users.request.LoginServReq;
import com.zhiwei.codesecurity.service.users.response.AddUserServRlt;
import com.zhiwei.codesecurity.service.users.response.LoginRlt;
import com.zhiwei.codesecurity.service.users.response.QueryUserServRlt;
import com.zhiwei.codesecurity.web.api.user.request.*;
import com.zhiwei.codesecurity.web.api.user.response.LoginResponse;
import com.zhiwei.codesecurity.web.common.base.BaseController;
import com.zhiwei.codesecurity.web.common.base.BaseRequest;
import com.zhiwei.codesecurity.web.common.base.BaseResponse;
import com.zhiwei.codesecurity.web.common.base.RequestHead;
import com.zhiwei.codesecurity.common.constants.ResourcesPropertiesConstants;
import com.zhiwei.codesecurity.web.common.utils.ResponseUtil;
import com.zhiwei.codesecurity.web.handler.UserCenterHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserCenterHandler userCenterHandler;

    @Autowired
    private IUserService userService;

    @RequestMapping("/test")
    @ResponseBody
    public BaseResponse test() {
        logger.info(">>> process: 测试数据|ResourcesPropertiesConstants.GIT_DOWNLOAD_DIR={}",
                ResourcesPropertiesConstants.GIT_DOWNLOAD_DIR);
        return ResponseUtil.getSuccessResponse();
    }

    @RequestMapping("/login")
    @ResponseBody
    public BaseResponse login(@RequestBody RequestHead head, @Valid @RequestBody LoginReq req,BindingResult result) {
        logger.info(">>> process:用户登录|userAccount={}", req.getUserAccount());

        if (ResponseUtil.existsParamsError(result)) {
            return ResponseUtil.getErrorParams(result);
        }

        if (StringUtils.isBlank(head.getOsType())) {
            return ResponseUtil.getErrorBusi("没有提供系统来源!");
        }

        // 执行登录逻辑
        LoginServReq loginServReq = new LoginServReq();
        loginServReq.setLoginName(req.getUserAccount());
        loginServReq.setLoginPwd(req.getPassWord());
        loginServReq.setSourceType(head.getOsType());
        loginServReq.setSystemType(ReloadAbleProperty.getProperty("codesecurity.partnerId"));
        ServiceResponse<LoginRlt> loginRlt = userService.doLogin(loginServReq);
        if (loginRlt.isError()) {
            // 登录失败
            logger.warn("=== process:用户登录|失败|userAccount={},errMsg={}", req.getUserAccount(), loginRlt.getValue());
            return ResponseUtil.getErrorBusi("用户登录失败!");
        }

        LoginResponse loginResponse = new LoginResponse();
        LoginRlt rlt = loginRlt.getData();
        loginResponse.setToken(rlt.getTokenId());
        loginResponse.setUserId(rlt.getMemberNo());
        loginResponse.setUserName(rlt.getUserName());
        loginResponse.setUserMail(rlt.getUserMail());
        loginResponse.setTeamId(rlt.getTeamId());

        ServiceResponse<LoginResponse> loginResult = new ServiceResponse<>(loginResponse);
        return ResponseUtil.getSuccessResponse(loginResult.getData());
    }

    @RequestMapping("/logout")
    @ResponseBody
    public BaseResponse logout(@RequestBody RequestHead head, @RequestBody BaseRequest req) {
        ServiceResponse<NullObjectResp> logoutRlt = userCenterHandler.doLogout(head, req);

        if (logoutRlt.isSuccess()) {
            logger.debug("=== process:用户退出登录|userId={}", req.getUserId());
            return ResponseUtil.getSuccessResponse();
        } else {
            logger.warn("=== process:用户退出登录|异常|userId={},logoutRlt={}", req.getUserId(), logoutRlt.toString());
            return ResponseUtil.getError(ResultCode.EXCEPTION_BUSINESS.getKey(), logoutRlt.getValue());

        }
    }

    /**
     * 添加用户
     * @param head
     * @param addUserReq
     * @param result
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public BaseResponse addUser(@RequestBody RequestHead head, @Valid @RequestBody AddUserReq addUserReq,
                                BindingResult result) {
        logger.info(">>> process: 用户添加|user_account={}", addUserReq.getUserAccount());
        if (ResponseUtil.existsParamsError(result)) {
            return ResponseUtil.getErrorParams(result);
        }

        Users users = new Users();
        BeanUtil.copyPropertiesQuietly(addUserReq, users);
        users.setId(IdWorker.generate());
        users.setUserId(UUIDUtil.getUUID());

        ServiceResponse<AddUserServRlt> serviceResponse = userService.addUser(users);
        if (serviceResponse.isError()) {
            logger.warn("用户添加失败, returnCode={}, returnMsg={}", serviceResponse.getCode(), serviceResponse.getMsg());
            return ResponseUtil.getErrorBusi(serviceResponse.getMsg());
        }
        return ResponseUtil.getSuccessResponse(serviceResponse.getData());
    }

    /**
     * 修改用户
     * @param head
     * @param modifyUserReq
     * @param result
     * @return
     */
    @RequestMapping("/modify")
    @ResponseBody
    public BaseResponse modifyUser(@RequestBody RequestHead head, @Valid @RequestBody ModifyUserReq modifyUserReq,
                                   BindingResult result) {
        logger.info(">>> process: 用户添加|user_id={}", modifyUserReq.getUserId());
        if (ResponseUtil.existsParamsError(result)) {
            return ResponseUtil.getErrorParams(result);
        }

        Users users = new Users();
        BeanUtil.copyPropertiesQuietly(modifyUserReq, users);
        ServiceResponse<NullObjectResp> serviceResponse = userService.modifyUser(users);
        if (serviceResponse.isError()) {
            logger.warn("用户修改失败, returnCode={}, returnMsg={}", serviceResponse.getCode(), serviceResponse.getMsg());
            return ResponseUtil.getErrorBusi(serviceResponse.getMsg());
        }

        return ResponseUtil.getSuccessResponse();
    }

    @RequestMapping("/query")
    @ResponseBody
    public BaseResponse queryUser(@RequestBody RequestHead head, @Valid @RequestBody QueryUserReq queryUserReq,
                                  BindingResult result) {
        logger.info(">>> process: 用户查询|user_id={}", queryUserReq.getUserId());
        if (ResponseUtil.existsParamsError(result)) {
            return ResponseUtil.getErrorParams(result);
        }

        ServiceResponse<QueryUserServRlt> serviceResponse = userService.queryUser(queryUserReq.getUserId());
        if (serviceResponse.isError()) {
            logger.warn("用户查询失败, returnCode={}, returnMsg={}", serviceResponse.getCode(), serviceResponse.getMsg());
            return ResponseUtil.getErrorBusi(serviceResponse.getMsg());
        }

        return ResponseUtil.getSuccessResponse(serviceResponse.getData());
    }

    @RequestMapping("/delete")
    @ResponseBody
    public BaseResponse deleteUser(@RequestBody RequestHead head, @Valid @RequestBody DeleteUserReq deleteUserReq,
                                   BindingResult result) {
        logger.info(">>> process: 用户删除|user_id={}", deleteUserReq.getUserId());
        if (ResponseUtil.existsParamsError(result)) {
            return ResponseUtil.getErrorParams(result);
        }

        ServiceResponse<NullObjectResp> serviceResponse = userService.deleteUser(deleteUserReq.getUserId());
        if (serviceResponse.isError()) {
            logger.warn("用户删除失败, returnCode={}, returnMsg={}", serviceResponse.getCode(), serviceResponse.getMsg());
            return ResponseUtil.getErrorBusi(serviceResponse.getMsg());
        }

        return ResponseUtil.getSuccessResponse();
    }
}
